package org.dizena.modules.master.web;

import org.apache.shiro.session.Session;
import org.crazycake.shiro.RedisSessionDAO;
import org.dizena.base.avo.resp.JqGridResp;
import org.dizena.base.enums.Constant;
import org.dizena.modules.master.avo.LineUserVo;
import org.dizena.modules.master.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Controller
@RequestMapping("master/line")
public class MasterLineController
{

    @Resource
    private RedisSessionDAO shiroRedisSessionDao;

    @GetMapping("list")
    public String line(Model m)
    {

        return "master/line/list";
    }

    @PostMapping("list")
    @ResponseBody
    public JqGridResp<LineUserVo> line()
    {
        List<LineUserVo> list = new ArrayList<>();
        Collection<Session> sessions = shiroRedisSessionDao.getActiveSessions();
        for (Session session : sessions)
        {
            LineUserVo data = new LineUserVo();
            data.setId(session.getId().toString());
            data.setHost(session.getHost());
            data.setStartTime(session.getStartTimestamp().getTime());
            data.setLastAccessTime(session.getLastAccessTime().getTime());
            Object obj = session.getAttribute(Constant.CurrentUser);
            if (obj instanceof User)
            {
                User user = (User) obj;
                data.setUid(user.getId());
                data.setAccount(user.getAccount());
                data.setNickname(user.getNickname());
            }
            list.add(data);
        }
        JqGridResp<LineUserVo> result = new JqGridResp<>();
        result.setCode(200);
        result.setMsg("ok");
        result.setRows(list);
        result.setTotal(1L);
        result.setPage(1L);
        result.setRecordsInt(list.size());
        return result;
    }

    @GetMapping("del")
    public String del(@RequestParam("id") String id)
    {
        Collection<Session> sessions = shiroRedisSessionDao.getActiveSessions();
        sessions.forEach(s ->
        {
            String sid = s.getId().toString();
            if (id.equals(sid))
            {
                shiroRedisSessionDao.delete(s);
            }
        });
        return "redirect:/master/line/list";
    }


}
